package com.nageoffer.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.dao.entity.UserDO;
import com.nageoffer.shortlink.admin.dao.mapper.UserMapper;
import com.nageoffer.shortlink.admin.dto.req.UserLoginReqDTO;
import com.nageoffer.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.nageoffer.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.nageoffer.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.nageoffer.shortlink.admin.dto.resp.UserRespDTO;
import com.nageoffer.shortlink.admin.service.GroupService;
import com.nageoffer.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.nageoffer.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KET;
import static com.nageoffer.shortlink.admin.common.enums.UserErrorCodeEnum.*;

/**
 * 用户接口实现层
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;

    public UserRespDTO getUserByUsername(String username) {
//        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
//                .eq(UserDO::getUsername, username);
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        UserRespDTO result = new UserRespDTO();
        if (userDO != null) {
            BeanUtils.copyProperties(userDO, result);
            return result;
        } else {
            return null;
        }
    }

    @Override
    public Boolean availableUsernmae(String username) {
        //如果布隆过滤器中包含该用户名，则返回 false
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO reqParam) {
        if (reqParam.getUsername() == null || reqParam.getUsername().isEmpty()) {
            throw new ClientException(USER_SAVE_ERROR);
        }
        if (!availableUsernmae(reqParam.getUsername())) {
            throw new ClientException(USER_IS_EXSIT);
        }
        //将用户信息插入数据库
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KET + reqParam.getUsername());
        try {
            //获取锁进行注册
            if (lock.tryLock()) {
                int inserted = baseMapper.insert(BeanUtil.toBean(reqParam, UserDO.class));
                if (inserted < 1) {
                    throw new ClientException(USER_SAVE_ERROR);
                }
                userRegisterCachePenetrationBloomFilter.add(reqParam.getUsername());
                groupService.saveGroup(reqParam.getUsername(),"默认分组");
                return;
            }//没获取到锁表明有用户获取到锁并且注册成功
            throw new ClientException(USER_SAVE_ERROR);
        } finally {
            lock.unlock();
        }
        //将用户名加入布隆过滤器中

    }

    @Override
    public void updateUserInfo(UserUpdateReqDTO reqParam) {
        //用UserId更新用户信息是不对的，因为分片规则是根据username来分片的
//        LambdaUpdateWrapper<UserDO> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(UserDO::getId, reqParam.getId());

        //分片规则是根据Username 来分片的，所以如果用户名相同，则更新成功
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, reqParam.getUsername());
        baseMapper.update(BeanUtil.toBean(reqParam, UserDO.class), updateWrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO reqParam) {
        UserDO userDO = baseMapper.selectOne(Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, reqParam.getUsername())
                .eq(UserDO::getPassword, reqParam.getPassword())
                .eq(UserDO::getDelFlag, 0));
        if (userDO == null) {
            throw new ClientException(USER_IS_NOT_EXSIT);
        }
        Boolean hasLogin = stringRedisTemplate.hasKey("login_" + reqParam.getUsername());
        if (hasLogin != null && hasLogin) {
            throw new ClientException("用户已登录");
        }
        //防止用户重复登录token重复刷新，保持用户的唯一token
        String uuid = UUID.randomUUID().toString();
        //直接存储 Java 对象会导致序列化问题，而转换为 JSON 字符串可以确保数据能够正确地被存储和后续解析使用。
        stringRedisTemplate.opsForHash().put("login_" + reqParam.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire("login_" + reqParam.getUsername(), 30L, TimeUnit.DAYS);

        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_" + username, token) != null;

    }

    @Override
    public void logout(String username,String token) {
        if(checkLogin(username, token)){
            stringRedisTemplate.opsForHash().delete("login_" + username, token);
            return;
        }
        throw new ClientException("用户未登录或无Token");
    }

}
